package com.dlink.sqljobsync.utils;

import com.dlink.sqljobsync.propertie.DlinkSqlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.List;
import java.util.Properties;

/**
 * @author ASUS
 */

@Component
@Slf4j
public class Utility {

    @Autowired
    DlinkSqlProperties dlinkSqlProperties;

    @Autowired
    ApplicationEventMulticaster eventMulticaster;
    /**
	 * 读取数据的配置
	 * 
	 * @return
	 */
	public  Properties loadProperties() throws IOException {
        //获取当前应用路径
        String javafxRuntimePath = null;
        File file = null;
        if(dlinkSqlProperties.isStatus()){
            try {
                file = ResourceUtils.getFile(dlinkSqlProperties.getFilePath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }else{
            //获取classpath下默认snowFlake.conf
            try {
                file = ResourceUtils.getFile("classpath:" + dlinkSqlProperties.getFilePath());
            } catch (FileNotFoundException e) {
                javafxRuntimePath = System.getProperty("user.dir");
                file = new File(javafxRuntimePath, dlinkSqlProperties.getFilePath());
            }
        }

		Properties properties = new Properties();
        String fileName = dlinkSqlProperties.getFilePath();
        FileInputStream stream = null;
        if (file.exists()) {
			try {
				stream = new FileInputStream(file);
				properties.load(stream);
			} catch (Exception ex) {
                log.error("读取配置文件出错", fileName);
			}finally {
			    if(stream != null){
                    stream.close();
                }
            }
		}else{
            try {
                //如果没有配置 DlinkSqlSync.conf文件，默认自动创建
                file.createNewFile();
                properties.setProperty("lastTimestamp_date_stat", String.valueOf(System.currentTimeMillis()));
                saveProperties(properties, file.getPath());
                log.error("读取配置文件不存在,重新创建配置文件！", fileName);
                throw new FileNotFoundException("读取配置文件不存在,重新创建配置文件....");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return properties;
	}

	/**
	 * 保存配置文件
	 * 
	 * @param properties
	 * @param fileName
	 */
	public void saveProperties(Properties properties, String fileName) {
        File file = new File(fileName);
		try {
			FileOutputStream stream = new FileOutputStream(file);
			properties.store(stream, null);
			stream.flush();
			stream.close();
		} catch (Exception ex) {
            log.error("存储配置文件出错", fileName);
		}
	}

   /**
     * 读取目录下的所有文件
     * @param dir
     * 目录
     * @param fileNames
     * 保存文件名的集合
     * @return
     */

    public void findFileList(File dir, List<String> fileNames) {
        if (!dir.exists() || !dir.isDirectory()) {// 判断是否存在目录
            return;
        }
        String[] files = dir.list();// 读取目录下的所有目录文件信息
        for (int i = 0; i < files.length; i++) {// 循环，添加文件名或回调自身
            File file = new File(dir, files[i]);
            if (file.isFile()) {// 如果文件
                fileNames.add(dir + "\\" + file.getName());// 添加文件全路径名
            } else {// 如果是目录
                findFileList(file, fileNames);// 回调自身继续查询
            }
        }
    }

    /**
     * 读取文件的内容
     * @param file
     * @return
     */
    public StringBuffer getReadFileTxt(String file){
        StringBuffer stringBuffer = new StringBuffer();
        FileInputStream fip = null;
        InputStreamReader reader = null;
        try {
            fip = new FileInputStream(file);
            reader = new InputStreamReader(fip, "UTF-8");
            while (reader.ready()) {
                stringBuffer.append((char) reader.read());
                // 转成char加到StringBuffer对象中
            }
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(reader != null && fip != null){
                try {
                    reader.close();
                    fip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuffer;
    }

}
